// 2025/8/18
// 合并k个已排序的链表

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类vector 
     * @return ListNode类
     */
    ListNode* merge(ListNode* list1, ListNode* list2)
    {
        ListNode head(0), *cur = &head;
        while(list1 && list2)
        {
            if(list1->val < list2->val)
            {
                cur->next = list1;
                list1 = list1->next;
            }
            else 
            {
                cur->next = list2;
                list2 = list2->next;
            }
            cur = cur->next;
            cur->next = nullptr;
        }
        if(list1)
            cur->next = list1;
        else
            cur->next = list2;
        return head.next;
    }
    
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // write code here
        int n = lists.size();
        if(n == 0) return nullptr;
        for(int i = 1; i < n; i++)
        {
            lists[0] = merge(lists[0], lists[i]);
        }
        return lists[0];
    }
};